﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;

namespace Casamiel.API.Infrastructure.Middlewares
{
    /// <summary>
    /// 
    /// </summary>
    public class FailingMiddleware
    {
        private readonly RequestDelegate _next;
        private bool _mustFail;
        private readonly FailingOptions _options;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="next"></param>
        /// <param name="options"></param>
        public FailingMiddleware(RequestDelegate next, FailingOptions options)
        {
            _next = next;
            _options = options;
            _mustFail = false;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            var path = context.Request.Path;
            if (path.Equals(_options.ConfigPath, StringComparison.OrdinalIgnoreCase))
            {
                await ProcessConfigRequest(context).ConfigureAwait(false);
                return;
            }
            if (MustFail(context))
            {
                context.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
                context.Response.ContentType = "text/plain";
                await context.Response.WriteAsync("Failed due to FailingMiddleware enabled.").ConfigureAwait(false);
            }
            else
            {
                await _next.Invoke(context).ConfigureAwait(false);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private bool MustFail(HttpContext context)
        {
            return _mustFail &&
                (_options.EndpointPaths.Any(x => x == context.Request.Path.Value)
                || _options.EndpointPaths.Count == 0);
        }
        private async Task ProcessConfigRequest(HttpContext context)
        {
            var enable = context.Request.Query.Keys.Any(k => k == "enable");
            var disable = context.Request.Query.Keys.Any(k => k == "disable");
            if (enable && disable)
            {
                throw new ArgumentException("Must use enable or disable querystring values, but not both");
            }
            if (disable)
            {
                _mustFail = false;
                await SendOkResponse(context, string.Format(CultureInfo.CurrentCulture,"FailingMiddleware is {0}", _mustFail ? "enable" : "disable")).ConfigureAwait(false);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        private async Task SendOkResponse(HttpContext context, string message)
        {
            context.Response.StatusCode = (int)System.Net.HttpStatusCode.OK;
            context.Response.ContentType = "text/plain";
            await context.Response.WriteAsync(message).ConfigureAwait(false);
        }
    }
}
